package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是Controller层的请求，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //获取token
        String token = request.getHeader("authorization");
        //判断token是否为空，如果为空，则未登录，返回登录页面
        if (StringUtils.isEmpty(token)){
            response.setStatus(401);
            return false;
        }
        //如果不为空则解析token,解析失败，返回登录页面，
        Claims claims;
        try {
            claims =  tokenService.parseToken(token);
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
        //获取用户信息

        if (MapUtil.isEmpty(claims)){
            response.setStatus(401);
            return false;
        }
        //存入threadlocal中
        Long o = Long.valueOf(String.valueOf(claims.get("userId")));
        UserThreadLocal.set(o);
        // 解析成功，放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        UserThreadLocal.remove();
    }
}
